package cn.wolfcode;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ProtocolException;
import java.net.URLDecoder;

public class LearnHttpClient {
    /**
     * Http Get 下载文件示例
     */
    public static void httpGetDownload() {
        CloseableHttpResponse response = null;
        try {
            // 创建 HttpGet 对象
            HttpGet httpGet = new HttpGet("http://localhost:8080/file/download");
            // 执行 Http Get 请求
            //response = HttpClientUtil.getHttpclient().execute(httpGet);
            // 从 headers 中获取文件名
//            String content = response.getHeader("Content-Disposition").getValue();
            String content = "";
            String filename = content.substring(content.lastIndexOf('=') + 1, content.lastIndexOf('.'));
            String suffix = content.substring(content.lastIndexOf('.'));
            // 将文件名转码
            filename = URLDecoder.decode(filename, "UTF-8");
            // 获取响应实体对象
            HttpEntity entity = response.getEntity();
            if (entity != null){
                // 获取输入流并且将保存下载的文件
                try (InputStream inputStream = entity.getContent();
                     FileOutputStream fileOutputStream = new FileOutputStream("d://" + filename + suffix)
                ) {
                    byte[] tmp = new byte[1024];
                    int l;
                    while ((l = inputStream.read(tmp)) != -1) {
                        fileOutputStream.write(tmp, 0, l);
                    }
                    fileOutputStream.flush();
                }
            }
            // 销毁流
            EntityUtils.consume(response.getEntity());
        } catch (IOException e) {
            e.getMessage();
        } finally {
            // 释放资源
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.getMessage();
                }
            }
        }
    }

    /** 测试 Main 方法 */
    public static void main(String[] args) {
        // 执行下载文件
        httpGetDownload();

}
}
